package com.jf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-02
 * Time:22:57
 */
public class ManageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("ManageFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("ManageFilter doFilter");
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        if (username != null) {
            System.out.println("Log:");
            System.out.println("Access username: " + username);
            System.out.println("Access IP: " + req.getRemoteAddr());
            System.out.println("Access URL: " + req.getRequestURL());
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("ManageFilter destroy");
    }
}
